<template>
  <div class="role-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>角色管理</span>
          <el-button type="primary" @click="handleAddRole">
            <el-icon><Plus /></el-icon>
            添加角色
          </el-button>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :model="searchForm" inline>
          <el-form-item label="角色名称">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入角色名称"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="权限级别">
            <el-select v-model="searchForm.level" placeholder="请选择权限级别" clearable>
              <el-option label="游客" :value="0" />
              <el-option label="普通用户" :value="1" />
              <el-option label="管理员" :value="2" />
              <el-option label="系统管理员" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleResetSearch">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 角色列表 -->
      <el-table :data="roleList" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="角色名称" width="200" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="level" label="权限级别" width="120">
          <template #default="scope">
            <el-tag :type="getLevelType(scope.row.level)">
              {{ getLevelName(scope.row.level) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280">
          <template #default="scope">
            <el-button size="small" @click="handleViewPermissions(scope.row)">
              <el-icon><Key /></el-icon>
              权限管理
            </el-button>
            <el-button size="small" type="primary" @click="handleEditRole(scope.row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="handleDeleteRole(scope.row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 编辑角色对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="isEdit ? '编辑角色' : '添加角色'"
      width="500px"
      :close-on-click-modal="false"
      @close="cancelEdit"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input 
            v-model="editForm.description" 
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述" 
          />
        </el-form-item>
        <el-form-item label="权限级别" prop="level">
          <el-select v-model="editForm.level" placeholder="请选择权限级别">
            <el-option label="游客" :value="0" />
            <el-option label="普通用户" :value="1" />
            <el-option label="管理员" :value="2" />
            <el-option label="系统管理员" :value="3" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelEdit">取消</el-button>
          <el-button type="primary" @click="submitEditForm" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 权限管理对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      :title="`管理角色权限 - ${currentRole?.name}`"
      width="800px"
      :close-on-click-modal="false"
      @close="cancelPermissionEdit"
    >
      <div v-loading="permissionLoading">
        <div class="permission-section">
          <h4>可分配权限</h4>
          <el-checkbox-group v-model="selectedPermissions">
            <div v-for="permissionType in permissionTypes" :key="permissionType.type" class="permission-type-section">
              <h5>{{ permissionType.name }}</h5>
              <div class="permission-list">
                <el-checkbox 
                  v-for="permission in permissionType.permissions" 
                  :key="permission.id" 
                  :label="permission.id"
                  class="permission-item"
                >
                  <span class="permission-name">{{ permission.name }}</span>
                  <span class="permission-desc">{{ permission.description }}</span>
                </el-checkbox>
              </div>
            </div>
          </el-checkbox-group>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelPermissionEdit">取消</el-button>
          <el-button type="primary" @click="submitPermissionForm" :loading="permissionSubmitLoading">
            保存权限
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getRoleList, 
  createRole, 
  updateRole, 
  deleteRole,
  assignRolePermissions,
  getRolePermissions
} from '@/api/role'
import { getAllPermissions } from '@/api/permission'

// 响应式数据
const loading = ref(false)
const roleList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索表单
const searchForm = reactive({
  name: '',
  level: null
})

// 编辑对话框
const editDialogVisible = ref(false)
const isEdit = ref(false)
const editFormRef = ref()
const submitLoading = ref(false)
const editForm = reactive({
  id: null,
  name: '',
  description: '',
  level: null
})

// 表单验证规则
const editFormRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 50, message: '角色名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '角色描述不能超过 200 个字符', trigger: 'blur' }
  ],
  level: [
    { required: true, message: '请选择权限级别', trigger: 'change' }
  ]
}

// 权限管理对话框
const permissionDialogVisible = ref(false)
const permissionLoading = ref(false)
const permissionSubmitLoading = ref(false)
const currentRole = ref(null)
const allPermissions = ref([])
const selectedPermissions = ref([])
const permissionTypes = ref([])

// 获取角色列表
const fetchRoleList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      ...searchForm
    }
    const response = await getRoleList(params)
    if (response.code === 200) {
      roleList.value = response.data.records
      total.value = response.data.total
    } else {
      ElMessage.error(response.message || '获取角色列表失败')
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchRoleList()
}

// 重置搜索
const handleResetSearch = () => {
  searchForm.name = ''
  searchForm.level = null
  currentPage.value = 1
  fetchRoleList()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchRoleList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchRoleList()
}

// 添加角色
const handleAddRole = () => {
  isEdit.value = false
  editForm.id = null
  editForm.name = ''
  editForm.description = ''
  editForm.level = null
  editDialogVisible.value = true
}

// 编辑角色
const handleEditRole = (row) => {
  isEdit.value = true
  editForm.id = row.id
  editForm.name = row.name
  editForm.description = row.description
  editForm.level = row.level
  editDialogVisible.value = true
}

// 提交表单
const submitEditForm = async () => {
  try {
    await editFormRef.value.validate()
    submitLoading.value = true
    
    const data = {
      name: editForm.name,
      description: editForm.description,
      level: editForm.level
    }
    
    let response
    if (isEdit.value) {
      response = await updateRole(editForm.id, data)
    } else {
      response = await createRole(data)
    }
    
    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '角色更新成功' : '角色创建成功')
      editDialogVisible.value = false
      fetchRoleList()
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    if (error.message) {
      ElMessage.error(error.message)
    }
  } finally {
    submitLoading.value = false
  }
}

// 取消编辑
const cancelEdit = () => {
  editDialogVisible.value = false
  editFormRef.value?.resetFields()
}

// 删除角色
const handleDeleteRole = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色 "${row.name}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const response = await deleteRole(row.id)
    if (response.code === 200) {
      ElMessage.success('角色删除成功')
      fetchRoleList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除角色失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 权限管理
const handleViewPermissions = async (row) => {
  currentRole.value = row
  permissionDialogVisible.value = true
  await loadPermissions()
}

// 加载权限数据
const loadPermissions = async () => {
  permissionLoading.value = true
  try {
    // 获取所有权限
    const allPermResponse = await getAllPermissions()
    if (allPermResponse.code === 200) {
      allPermissions.value = allPermResponse.data
      
      // 按类型分组权限
      const grouped = {}
      allPermResponse.data.forEach(permission => {
        if (!grouped[permission.permissionType]) {
          grouped[permission.permissionType] = []
        }
        grouped[permission.permissionType].push(permission)
      })
      
      permissionTypes.value = Object.keys(grouped).map(type => ({
        type,
        name: getPermissionTypeName(type),
        permissions: grouped[type]
      }))
    }
    
    // 获取角色已有权限
    if (currentRole.value) {
      const rolePermResponse = await getRolePermissions(currentRole.value.id)
      if (rolePermResponse.code === 200) {
        selectedPermissions.value = rolePermResponse.data
      }
    }
  } catch (error) {
    console.error('加载权限数据失败:', error)
    ElMessage.error('加载权限数据失败')
  } finally {
    permissionLoading.value = false
  }
}

// 提交权限设置
const submitPermissionForm = async () => {
  permissionSubmitLoading.value = true
  try {
    const response = await assignRolePermissions(currentRole.value.id, selectedPermissions.value)
    if (response.code === 200) {
      ElMessage.success('权限设置成功')
      permissionDialogVisible.value = false
    } else {
      ElMessage.error(response.message || '权限设置失败')
    }
  } catch (error) {
    console.error('提交权限设置失败:', error)
    ElMessage.error('权限设置失败')
  } finally {
    permissionSubmitLoading.value = false
  }
}

// 取消权限编辑
const cancelPermissionEdit = () => {
  permissionDialogVisible.value = false
  selectedPermissions.value = []
  currentRole.value = null
}

// 辅助函数
const getLevelType = (level) => {
  const types = { 0: 'info', 1: '', 2: 'warning', 3: 'danger' }
  return types[level] || ''
}

const getLevelName = (level) => {
  const names = { 0: '游客', 1: '普通用户', 2: '管理员', 3: '系统管理员' }
  return names[level] || '未知'
}

const getPermissionTypeName = (type) => {
  const names = { 'USER': '用户权限', 'ADMIN': '管理权限', 'SYSTEM': '系统权限' }
  return names[type] || type
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString()
}

// 初始化
onMounted(() => {
  fetchRoleList()
})
</script>

<style scoped>
.role-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-area {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}

.permission-section {
  max-height: 500px;
  overflow-y: auto;
}

.permission-type-section {
  margin-bottom: 20px;
}

.permission-type-section h5 {
  margin: 0 0 10px 0;
  color: #409eff;
  border-bottom: 1px solid #e4e7ed;
  padding-bottom: 5px;
}

.permission-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 10px;
}

.permission-item {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  padding: 8px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #fafafa;
}

.permission-name {
  font-weight: bold;
  color: #303133;
}

.permission-desc {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
}
</style>